﻿using Newtonsoft.Json;
using System.Text;
using Zhao.Common.Applet.Model;

namespace Zhao.Common.Applet
{
    /// <summary>
    /// 调用微信API帮助类
    /// </summary>
    public class WechatAPIClient
    {
        private readonly string appid;

        public readonly string secret;


        public WechatAPIClient(string appid, string secret)
        {
            this.appid = appid;
            this.secret = secret;
        }

        /// <summary>
        /// 登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程
        /// https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
        /// </summary>
        /// <param name="js_code">参数</param>
        /// <returns></returns>
        public async Task<Code2SessionResult?> GetCode2Session(string js_code)
        {
            var result = await Get($"https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}&grant_type=authorization_code");
            return JsonConvert.DeserializeObject<Code2SessionResult>(result);
        }

        public async Task<PhoneInfoResult> getUserPhoneNumberByCode(string code, string accessToken)
        {
            var result = await Post($"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={accessToken}",new {code= code });
            return JsonConvert.DeserializeObject<PhoneInfoResult>(result);
        }

        /// <summary>
        /// 获取token以便后续获取用户手机号码做准备
        /// </summary>
        /// <returns></returns>
        public async Task<AccessToken> GtoToKen()
        {
            var result = await Get($"https://api.weixin.qq.com/cgi-bin/token?appid={appid}&secret={secret}&grant_type=client_credential");
            return JsonConvert.DeserializeObject<AccessToken>(result);
        }


        /// <summary>
        /// 内部使用的通用方法
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        static async Task<string> Get(string url)
        {
            try
            {
                var httpClient = new HttpClient();
                HttpResponseMessage response = await httpClient.GetAsync(url);
                return response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : ""; ;
            }
            catch (Exception ex)
            {
                throw new Exception("Get 请求出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 泛型post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        static async Task<string> Post<T>(string url, T data)
        {
            try
            {
                using var httpClient = new HttpClient();
                string json = JsonConvert.SerializeObject(data);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(url, content);
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                throw new Exception($"POST请求出错：{ex.Message}");
            }
        }

    }
}
